<template>
  <!-- 扫描策略 -->
  <div class="friend-link-container">
    <!-- 添加搜索区域 -->
    <div class="search-container">
      <el-form :inline="true" class="search-form">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="搜索字段">
              <el-select v-model="selectedField" placeholder="请选择" clearable>
                <el-option v-for="field in searchFields" :key="field.value" :label="field.label" :value="field.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="搜索内容">
              <el-input v-model="searchQuery" placeholder="请输入搜索内容" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-button type="primary" plain @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <el-table :data="filteredData" row-key="id" table-layout="auto" style="width: 100%">
      <el-table-column type="index" label="序号" width="80" :index="indexMethod" />
      <el-table-column prop="policyName" label="策略名称" width="180" />
      <el-table-column prop="content" label="策略内容" show-overflow-tooltip width="200px" />

      <el-table-column label="扫描类型" width="120">
        <template #default="{row}">
          <el-tag :type="getScanTypeTagType(row.scanType)">
            {{ getScanTypeLabel(row.scanType) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="扫描频率" width="120">
        <template #default="{row}">
          <el-tag :type="getFrequencyTagType(row.timerSetting)">
            {{ getFrequencyLabel(row.timerSetting) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="startTime" label="开始时间" width="200" />
      <el-table-column prop="notes" label="备注" width="200" />

      <el-table-column label="操作" width="180">
        <template #default="{row}">
          <el-button type="info" size="small" @click="handleDelete(row.id)">隐藏</el-button>
          <el-button type="danger" size="small" @click="handleDelete(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination v-model:current-page="pagination.current" v-model:page-size="pagination.size" :page-sizes="[10, 20, 30, 50]" :total="pagination.total" layout="total, sizes, prev, pager, next, jumper" @current-change="handleCurrentChange" @size-change="handleSizeChange" style="margin-top: 20px;" />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'

// 本地存储Key
const STORAGE_KEY = 'scan_strategies_data'

// 响应式数据
const allData = ref([])
const searchQuery = ref('')
const selectedField = ref('')  // 默认搜索字段
// 新增响应式数据
const searchFields = [
  { label: '策略名称', value: 'policyName' },

]

// 分页配置
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 计算属性
const filteredData = computed(() => {

  // 如果没有搜索词，返回所有数据
  if (!searchQuery.value) {
    const start = (pagination.current - 1) * pagination.size
    return allData.value.slice(start, start + pagination.size)
  }

  // 当有搜索条件时进行过滤
  // 原始数据过滤
  let filteredList = allData.value
  if (searchQuery.value && selectedField.value) {
    filteredList = allData.value.filter(item => {
      const fieldValue = String(item[selectedField.value] || '')
      return fieldValue.toLowerCase().includes(searchQuery.value.toLowerCase())
    })
  }

  // 有搜索词时进行过滤
  const query = searchQuery.value.toLowerCase()
  const filtered = allData.value.filter(item =>
    (item.policyName && item.policyName.toLowerCase().includes(query)) ||
    (item.content && item.content.toLowerCase().includes(query)) ||
    (item.notes && item.notes.toLowerCase().includes(query))
  )

  // 更新分页总数
  pagination.total = filtered.length

  // 分页处理
  const start = (pagination.current - 1) * pagination.size
  return filtered.slice(start, start + pagination.size)
})

// 搜索方法
const handleSearch = () => {
  if (!selectedField.value) {
    ElMessage.error('请选择搜索条件后查询')
    return
  }
  if (!searchQuery.value) {
    ElMessage.error('请输入搜索内容')
    return
  }
  pagination.current = 1  // 搜索后重置到第一页
}
// 重置方法
const handleReset = () => {
  selectedField.value = ''
  searchQuery.value = ''
  pagination.current = 1
}

// 辅助函数：获取扫描类型标签
const getScanTypeLabel = (type) => {
  const map = {
    '1': '快速扫描',
    '2': '深度扫描',
    '3': '全面扫描',
    '4': '自定义扫描'
  }
  return map[type] || '未知类型'
}

// 辅助函数：获取扫描类型标签样式
const getScanTypeTagType = (type) => {
  const map = {
    '1': 'success',
    '2': 'warning',
    '3': 'danger',
    '4': 'info'
  }
  return map[type] || ''
}

// 辅助函数：获取扫描频率标签
const getFrequencyLabel = (freq) => {
  const map = {
    '1': '仅一次',
    '2': '每小时',
    '3': '每天',
    '4': '每周',
    '5': '每月'
  }
  return map[freq] || '未知频率'
}

// 辅助函数：获取扫描频率标签样式
const getFrequencyTagType = (freq) => {
  const map = {
    '1': 'info',
    '2': '',
    '3': 'success',
    '4': 'warning',
    '5': 'danger'
  }
  return map[freq] || ''
}

const indexMethod = (index) => {
  return index + 1
}

// 生命周期钩子
onMounted(() => {
  loadFromStorage()
  setupDataSync();
})
const setupDataSync = () => {
  window.addEventListener('storage', (event) => {
    if (event.key === 'scan_strategies') {
      loadStrategies();
      ElMessage.success('策略数据已更新');
    }
  });
};

// 数据操作方法
const loadFromStorage = () => {
  try {
    const saved = localStorage.getItem(STORAGE_KEY)
    const parsedData = saved ? JSON.parse(saved) : []

    // 确保始终返回数组
    allData.value = Array.isArray(parsedData) ? parsedData : []


    const data1 = {
      id: Date.now(),
      policyName: '每周全面扫描',
      content: '扫描所有友链',
      scanType: '3',
      timerSetting: '4',
      startTime: '2025-05-01',
      notes: '每周一凌晨扫描'
    }
    const data2 = {
      id: Date.now() + 1,
      policyName: '每日快速扫描',
      content: '快速扫描重要友链',
      scanType: '1',
      timerSetting: '3',
      startTime: '2025-05-01',
      notes: '每天凌晨扫描'
    }
    allData.value.push(data1, data2)


    // 更新分页总数
    pagination.total = allData.value.length

  } catch (error) {
    console.error('数据解析失败:', error)
    allData.value = []
    pagination.total = 0
  }
}

const saveToStorage = () => {
  try {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(allData.value))
  } catch (error) {
    console.error('数据存储失败:', error)
    ElMessage.error('数据保存失败')
  }
}

// 隐藏操作
const handleHide = (id) => {
  ElMessage.info('隐藏操作: ' + id)
  // 实际项目中这里会更新状态
}

// 删除操作
const handleDelete = (id) => {
  allData.value = allData.value.filter(item => item.id !== id)
  saveToStorage()
  ElMessage.success('删除成功')

  // 更新分页总数
  pagination.total = allData.value.length

  // 如果删除后当前页没有数据，回到上一页
  if (filteredData.value.length === 0 && pagination.current > 1) {
    pagination.current -= 1
  }
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
}

const handleCurrentChange = (current) => {
  pagination.current = current
}
</script>

<style scoped>
.friend-link-container {
	padding: 20px;
	background: #fff;
	border-radius: 8px;
}

:deep(.el-table .cell) {
	width: max-content;
	display: inline-block;
}

.el-pagination {
	justify-content: flex-end;
	margin-top: 20px;
}

.search-container {
	margin-bottom: 20px;
}
</style>